<?php

    function getStringTheWayItIs($string)
    {
//        return (nl2br(str_replace(' ', '&nbsp;', $string)));
        return (nl2br($string));
    }

    function deleteDirectory($dirPath)
    {
        if (is_dir($dirPath))
        {
            $objects = scandir($dirPath);
            foreach ($objects as $object)
            {
                if ($obgeject != "." && $object != "..")
                {
                    if (filetype($dirPath . DIRECTORY_SEPARATOR . $object) == "dir")
                    {
                        deleteDirectory($dirPath . DIRECTORY_SEPARATOR . $object);
                    }
                    else
                    {
                        unlink($dirPath . DIRECTORY_SEPARATOR . $object);
                    }
                }
            }
            reset($objects);
            rmdir($dirPath);
        }
    }

    function getVideoEmbedUrl($video_id, $video_service = "youtube")
    {
        $url = "http://youtube.com/embed/$video_id";
        if ($video_service == "vimeo")
            $url = "http://vimeo.com/$video_id";

        return $url;
    }

    function getVideoThumb($video_id, $video_service = "youtube")
    {
        $url = "http://img.youtube.com/vi/$video_id/0.jpg";
        if ($video_service == "vimeo")
        {
            $hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/$video_id.php"));
            $url = $hash[0]['thumbnail_medium'];
        }

        return $url;
    }

    function getVideoServiceName($url)
    {
        if (strpos($url, "vimeo"))
        {
            $video_service = "vimeo";
            $exploded = explode("/", $url);
            $key = count($exploded) - 1;
            $video_id = $exploded[$key];
        }
        else
        {
            $video_service = "youtube";
            $exploded = explode("/", $url);
            $key = count($exploded) - 1;
            $video_id = $exploded[$key];
        }

        return array("video_id" => $video_id, "video_service" => $video_service);
    }

    function sksort(&$array, $subkey = "id", $sort_ascending = false)
    {

        if (count($array))
            $temp_array[key($array)] = array_shift($array);

        foreach ($array as $key => $val)
        {
            $offset = 0;
            $found = false;
            foreach ($temp_array as $tmp_key => $tmp_val)
            {
                if (!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
                {
                    $temp_array = array_merge((array) array_slice($temp_array, 0, $offset), array($key => $val), array_slice($temp_array, $offset)
                    );
                    $found = true;
                }
                $offset++;
            }
            if (!$found)
                $temp_array = array_merge($temp_array, array($key => $val));
        }

        if ($sort_ascending)
            $array = array_reverse($temp_array);
        else
            $array = $temp_array;
    }

    function getEventDate($date_array)
    {
        $test = json_decode($date_array);
        $decoded = (array) $test;
        foreach ($decoded["day"] as $key => $value)
        {
//            $new_time = ($value . "-" . $decoded["month"][$key] . "-" . $decoded["year"][$key]);
            $new_time = ($value . " " . $decoded["month"][$key] . " " . $decoded["year"][$key]);
//            prd($new_time);
//            if ($new_time < time())
//            {
//                $new_time = date("d M Y", ($new_time));
//                return $new_time;
//                break;
//            }
//                $new_time = date("d M Y", ($new_time));
            return $new_time;
        }
    }

    function getLatLonOnIPAddress($ip_addr = NULL)
    {
        if ($ip_addr == NULL)
            $ip_addr = $_SERVER['REMOTE_ADDR'];
        $geoplugin = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $ip_addr));

        if (is_numeric($geoplugin['geoplugin_latitude']) && is_numeric($geoplugin['geoplugin_longitude']))
        {

            $lat = $geoplugin['geoplugin_latitude'];
            $long = $geoplugin['geoplugin_longitude'];
        }

        return array(
            "latitude" => $lat,
            "longitude" => $long
        );
    }

    function getCurrentEventDistance($event_address, $current_ip = null, $distance_unit = "M", $unitRequired = TRUE)
    {
        $prepAddr = str_replace(' ', '+', $event_address);

        @$geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address=' . $prepAddr . '&sensor=false');
        $output = json_decode($geocode);
        if (empty($output->results))
            return "NA";
        $lat1 = $output->results[0]->geometry->location->lat;
        $lon1 = $output->results[0]->geometry->location->lng;

        if ($current_ip == NULL)
            $current_ip = $_SERVER["REMOTE_ADDR"];

        $current_lat_lon_arr = getLatLonOnIPAddress($current_ip);
        $lat2 = $current_lat_lon_arr["latitude"];
        $lon2 = $current_lat_lon_arr["longitude"];

        $theta = $lon1 - $lon2;
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $distance_unit = strtoupper($distance_unit);

        if ($distance_unit == "K")
        {
            $output = ($miles * 1.609344);
            $distance_unit = "km";
        }
        else if ($distance_unit == "M")
        {
            $output = ($miles * 0.8684);
            $distance_unit = "miles";
        }
        else
        {
            $output = $miles;
            $distance_unit = "miles";
        }

        if ($unitRequired == TRUE)
            return round($output, 2) . " " . $distance_unit;
        else
            return round($output, 2);
    }

    function getEventDistanceAway($event_address, $another_address, $distance_unit = "M")
    {
        $prepAddr = str_replace(' ', '+', $event_address);
        $prepAddr2 = str_replace(' ', '+', $another_address);

        $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address=' . $prepAddr . '&sensor=false');
//        prd($geocode);
        $geocode2 = file_get_contents('http://maps.google.com/maps/api/geocode/json?address=' . $prepAddr2 . '&sensor=false');

        $output = json_decode($geocode);
//        pr($output);
        if (empty($output->results))
            return "NA";
        $lat1 = $output->results[0]->geometry->location->lat;
        $lon1 = $output->results[0]->geometry->location->lng;

        $output2 = json_decode($geocode2);
        if (empty($output2->results))
            return "NA";
        $lat2 = $output2->results[0]->geometry->location->lat;
        $lon2 = $output2->results[0]->geometry->location->lng;

        $theta = $lon1 - $lon2;
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $distance_unit = strtoupper($distance_unit);

        if ($distance_unit == "K")
        {
            $result = ($miles * 1.609344);
        }
        else if ($distance_unit == "M")
        {
            $result = ($miles * 0.8684);
        }
        else
        {
            $result = $miles;
        }

        return round($result, 2);
    }

    function addLeadingZero($value)
    {
        return sprintf("%02d", $value);
    }

    function getFileExtension($file_name)
    {
        $exploded_name = explode(".", $file_name);
        $count_of_Array = count($exploded_name);
        $extension = $exploded_name[$count_of_Array - 1];
        return $extension;
    }

    function getShareWithFacebookLink($link)
    {
        $href = '<script>
            function fbs_click() 
            {
            u=location.href;t=document.title;window.open("http://www.facebook.com/sharer.php?u="+encodeURIComponent(u)+"&t="+encodeURIComponent(t),"sharer","toolbar=0,status=0,width=626,height=436");
            return false;
            }
            </script>
            <a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" onclick="return fbs_click()" target="_blank">' . $link . '</a>';

        return $href;
    }

    function getBrowserType()
    {
        $useragent = $_SERVER['HTTP_USER_AGENT'];
        if (preg_match('/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $useragent) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i', substr($useragent, 0, 4)))
            $returnValue = 'mobile';
        else
            $returnValue = 'desktop';

        return $returnValue;
    }

    function prn($var)
    {
        echo '<pre>';
        print_r($var);
        echo '</pre>';
    }

    function pr($var)
    {
        echo '<pre>';
        print_r($var);
        echo '</pre>';
    }

    function prd($var)
    {
        echo '<pre>';
        print_r($var);
        echo '</pre>';
        die;
    }

    function gcm($var)
    {
        if (is_object($var))
            $var = get_class($var);
        echo '<pre>';
        prn(get_class_methods($var));
        echo '</pre>';
    }

    function getActivationKey($string)
    {
        $key = md5($string);
        return $key;
    }

    function getClientBrowserName()
    {
        $u_agent = $_SERVER['HTTP_USER_AGENT'];
        $ub = '';
        if (preg_match('/MSIE/i', $u_agent))
        {
            $ub = "Internet Explorer";
        }
        elseif (preg_match('/Firefox/i', $u_agent))
        {
            $ub = "Mozilla Firefox";
        }
        elseif (preg_match('/Chrome/i', $u_agent))
        {
            $ub = "Google Chrome";
        }
        elseif (preg_match('/Safari/i', $u_agent))
        {
            $ub = "Apple Safari";
        }
        elseif (preg_match('/Flock/i', $u_agent))
        {
            $ub = "Flock";
        }
        elseif (preg_match('/Opera/i', $u_agent))
        {
            $ub = "Opera";
        }
        elseif (preg_match('/Netscape/i', $u_agent))
        {
            $ub = "Netscape";
        }

        return $ub;
    }

    function getClientOS()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];

        $os_platform = "Unknown OS Platform";

        $os_array = array(
            '/windows nt 6.2/i' => 'Windows 8',
            '/windows nt 6.1/i' => 'Windows 7',
            '/windows nt 6.0/i' => 'Windows Vista',
            '/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
            '/windows nt 5.1/i' => 'Windows XP',
            '/windows xp/i' => 'Windows XP',
            '/windows nt 5.0/i' => 'Windows 2000',
            '/windows me/i' => 'Windows ME',
            '/win98/i' => 'Windows 98',
            '/win95/i' => 'Windows 95',
            '/win16/i' => 'Windows 3.11',
            '/macintosh|mac os x/i' => 'Mac OS X',
            '/mac_powerpc/i' => 'Mac OS 9',
            '/linux/i' => 'Linux',
            '/ubuntu/i' => 'Ubuntu',
            '/iphone/i' => 'iPhone',
            '/ipod/i' => 'iPod',
            '/ipad/i' => 'iPad',
            '/android/i' => 'Android',
            '/blackberry/i' => 'BlackBerry',
            '/webos/i' => 'Mobile'
        );

        foreach ($os_array as $regex => $value)
        {

            if (preg_match($regex, $user_agent))
            {
                $os_platform = $value;
            }
        }

        return $os_platform;
    }

    function isLogged()
    {
        $x = new Zend_Auth_Storage_Session('User_Auth');
        $y = $x->read();
        @$user_id = $x->read()->user_id;
        if (empty($user_id))
            return false;
        else
            return true;
    }

    function createWebsiteName($fullName)
    {
        // pr($fullName);
        preg_replace('/\S+/', '_', $fullName);
        if (is_unique_name("memorials", "memorial_website_name", $fullName))
        {
            //pr($fullName);
            return $fullName;
        }
        else
        {

            return createWebsiteName($fullName . rand(1, 100));
        }
    }

    /*
      function(boolean) finds whether the name i unique or not
      $tableName - table name for searching within that table
      fieldName - searches within that field
      needleString - string to be matched with
     * ******************************************************* */

    function is_unique_name($tableName, $fieldName, $needleString)
    {

        $db = Zend_Registry::get('db');
        $record = $db->select()->from($tableName)->where("$fieldName = '" . $needleString . "'")->query()->fetch();

        if (!empty($record) && is_array($record))
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    function getLastQuery()
    {
        $db = Zend_Registry::get("db");
        print $db->getProfiler()->getLastQueryProfile()->getQuery();
        print_r($db->getProfiler()->getLastQueryProfile()->getQueryParams());
        $db->getProfiler()->setEnabled(false);
    }

    //    This is a function to get current page url
    function curPageURL()
    {
        $pageURL = 'http';

        if (isset($_SERVER["HTTPS"]) && $_SERVER['HTTPS'] != "off")
        {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80")
        {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        }
        else
        {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }


        return $pageURL;
    }

    function getUrl($value)
    {
        if (preg_match("/http/", $value))
            $url = $value;
        else
            $url = SITE_HTTP_URL . "/" . $value;
        return $url;
    }

    function getAdminUrl($value = "")
    {
        $url = SITE_HTTP_URL . "/admin/" . $value;
        return $url;
    }

    createCaptcha();

    function createCaptcha()
    {
        $arr = array(
            array("3 + 5" => "8"),
            array("7 - 2" => "5"),
            array("4 + 6" => "10"),
            array("9 - 7" => "2"),
        );

        $count = count($arr) - 1;
        $rand_num = rand("0", $count);

        foreach ($arr[$rand_num] as $key => $value)
        {
            define("CAPTCHA_QUESTION", $key);
            define("CAPTCHA_ANSWER", $value);
        }
    }

    function getEncryptedString($value, $action = "encode")
    {
        if ($action == "encode")
        {
            return base64_encode($value . USE_SALT);
        }
        else
        {
            $str = base64_decode($value);
            $new_str = str_replace(USE_SALT, "", $str);
            return $new_str;
        }
    }

    function getTimeAgo($time)
    {
        $etime = time() - $time;

        if ($etime < 1)
        {
//            return '0 seconds';
            return 'Just now';
        }

        $a = array(12 * 30 * 24 * 60 * 60 => 'year',
            30 * 24 * 60 * 60 => 'month',
            24 * 60 * 60 => 'day',
            60 * 60 => 'hour',
            60 => 'minute',
            1 => 'second'
        );

        foreach ($a as $secs => $str)
        {
            $d = $etime / $secs;
            if ($d >= 1)
            {
                $r = round($d);
                return $r . ' ' . $str . ($r > 1 ? 's' : '') . ' ago';
            }
        }
    }

    function getFacebookUsernameUrl($username)
    {
        $str = "http://www.facebook.com/$username";
        return $str;
    }

    function getTwitterUsernameUrl($username)
    {
        $str = "http://www.twitter.com/$username";
        return $str;
    }

    function getLinkedinUsernameUrl($username)
    {
        $str = "http://www.linkedin.com/$username";
        return $str;
    }

    function in_array_custom($needle, $haystack, $field)
    {

        foreach ($haystack as $val)
        {

            if ($val[$field] == $needle)
                return true;
        }

        return false;
    }

    function getEventImages($event_id)
    {
        $new_array = array();
        $dir_name = EVENT_IMAGE_PATH . "/" . getEncryptedString($event_id);
        if (is_dir($dir_name))
        {
            $all_images = scandir($dir_name);
            unset($all_images[0], $all_images[1]);

            foreach ($all_images as $key => $value)
            {
                $new_array[] = getUrl($dir_name . "/" . $value);
            }
        }
        else
        {
            $new_array[] = getUrl(EVENT_NO_IMAGE_FILE);
        }

        if (empty($new_array))
            $new_array[] = getUrl(EVENT_NO_IMAGE_FILE);

//        prd($new_array);
        return $new_array;
    }

    function getUserImage($user_id)
    {
        $image = MEMBER_IMAGE_PATH . "/" . $user_id . ".jpg";

        if (is_file($image))
            $image_url = getUrl($image);
        else
            $image_url = getUrl(MEMBER_NO_IMAGE_FILE);

        return $image_url;
    }

    function getShareWithFacebook($url)
    {
        $str = "https://www.facebook.com/sharer/sharer.php?u=" . rawurlencode($url);
        return $str;
    }

    function getShareWithTwitter($status)
    {
        $str = "http://twitter.com/home?status=" . rawurlencode($status);
        return $str;
    }

    function getShareWithLinkedin($url, $title, $summary)
    {
        $str = 'http://www.linkedin.com/shareArticle?mini=true&url=' . rawurlencode($url) . '&title=' . rawurlencode($title) . '&summary=' . rawurlencode($summary);
        return $str;
    }

?>